package com.xhsj.user.utils;

import com.google.common.collect.Lists;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * @Description 树形结构工具类
 * @Author suxiaolin
 * @Date 2020/9/2 14:44
 */
public class TreeUtils {


    public static void setSubChild(Object fatherList, Object list) {
        if (fatherList instanceof List && list instanceof List) {
            List<Object> father = (List<Object>) fatherList;
            List<Object> allList = (List<Object>) list;
            for (Object object : father) {
                List<Object> subChild = getSubChild(object, allList);
                if (!CollectionUtils.isEmpty(subChild)) {
                    Reflections.setFieldValue(object,"children",subChild);
                    allList.removeAll(subChild);
                    setSubChild(subChild, allList);
                }
            }

        }
    }


    public static List<Object> getSubChild(Object target, Object source) {
        List<Object> result = Lists.newArrayList();
        if (source instanceof List) {
            List<Object> list = (List<Object>) source;
            for (Object menu : list) {
                String id = String.valueOf(Reflections.getFieldValue(target, "id"));
                String parentId = String.valueOf(Reflections.getFieldValue(menu, "parentId"));
                if (id.equals(parentId)) {
                    result.add(menu);
                }
            }
//            Collections.sort(result, new Comparator<Object>() {
//
//                @Override
//                public int compare(Object o1, Object o2) {
//                    String sort = String.valueOf(Reflections.getFieldValue(o1, "orderNum"));
//                    Integer sort1 = Integer.parseInt(String.valueOf(Reflections.getFieldValue(o1, "orderNum")));
//                    Integer sort2 = Integer.parseInt(String.valueOf(Reflections.getFieldValue(o2, "orderNum")));
//                    int i = sort1.compareTo(sort2);
//                    return i;
//                }
//            });
        }
        return result;
    }
}
